//
//  WHRequestTools.m
//  GoldenManager
//
//  Created by 文 on 2018/6/25.
//  Copyright © 2018年 sanpu. All rights reserved.
//

#import "WHRequestTools.h"
#import "NSDictionary+NSArray+Addition.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import "WH_DESUtils.h"
#include <objc/runtime.h>
#import <AFNetworking/AFNetworking-umbrella.h>

#define SIGN_KEY @"78631BBBA614A3B51DFBF925B5917460"

@implementation WHRequestTools

+(void)uploadWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters uploadArrary:(NSArray *)uploaArrary success:(HttpSuccess)success failure:(HttpFailure)failure{
    //创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    manager.requestSerializer.timeoutInterval = 60;

    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
    long long  time = interval;
    NSMutableDictionary *paraDict = [[NSMutableDictionary alloc]init];
    NSString *sessionId = [[NSUserDefaults standardUserDefaults]objectForKey:@"sessionId"];
    if (sessionId != nil) {
        [paraDict setValue:sessionId forKey:@"sessionId"];
    }
    
    for (NSString *key in [parameters allKeys]) {
        [paraDict setValue:[parameters valueForKey:key] forKey:key];
    }
    
    NSString *reqDataStr = [paraDict stringValueForKey:@"reqData"];
     if (reqDataStr.length > 0) {
            NSString *reqEncryptStr = [WH_DESUtils encryptUseDESForData:reqDataStr needLogin:true];
            [paraDict setValue:reqEncryptStr forKey:@"reqData"];
        }

    NSLog(@"%@",paraDict);
    
    [manager POST:urlString parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSDictionary *uploadDic in uploaArrary) {
            NSString *key = [[uploadDic allKeys] objectAtIndex:0];
            [formData appendPartWithFileData:uploadDic[key] name:key fileName:[NSString stringWithFormat:@"%@.png",key] mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        success(responseDict);
//        DEBUG_Log(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DEBUG_Log(@"%@",error);
        failure(error);
    }];
    
}

+(void)uploadWithUrlStringForOSS:(NSString *)urlString parameters:(NSDictionary *)parameters uploadArrary:(NSArray *)uploaArrary success:(HttpSuccess)success failure:(HttpFailure)failure{
    //创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    manager.requestSerializer.timeoutInterval = 60;

    [manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSDictionary *uploadDic in uploaArrary) {
            NSString *key = [[uploadDic allKeys] objectAtIndex:0];
            [formData appendPartWithFileData:uploadDic[key] name:key fileName:[NSString stringWithFormat:@"%@.png",key] mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        success(responseDict);
//        DEBUG_Log(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DEBUG_Log(@"%@",error);
        failure(error);
    }];
    
}


#pragma mark - 将参数排序，得到用来签名的字符串（发送验证码接口使用公钥签名）
+(NSString*)getStringForSign:(NSDictionary*)paramDict andIsSendSMS:(BOOL)isSms{
    NSMutableArray *signArray = [[NSMutableArray alloc]init];
    for (NSString *keyStr in [paramDict allKeys]) {
        NSString *tempStr = [NSString stringWithFormat:@"%@=%@",keyStr,[paramDict stringValueForKey:keyStr]];
        [signArray addObject:tempStr];
    }
    //    DEBUG_Log(@"signArray（排序前）：%@",signArray);
    NSArray *newArrary = [signArray sortedArrayUsingSelector:@selector(compare:)];
    //    DEBUG_Log(@"signArray（排序后）：%@",newArrary);
    NSMutableString *sortString = [[NSMutableString alloc] init];
    for (int i = 0; i < newArrary.count; i ++) {
        [sortString appendString:newArrary[i]];
        [sortString appendString:@"&"];
    }
    
    NSString *keyStr = SIGN_KEY;
    NSString *privateKey = [[NSUserDefaults standardUserDefaults]objectForKey:@"privateKey"];
    if (privateKey.length > 0 && !isSms) {
        keyStr = privateKey;
    }
    
    [sortString appendString:[NSString stringWithFormat:@"key=%@",keyStr]];
//    DEBUG_Log(@"用来签名的key:%@",keyStr);
    return sortString;
}

+ (NSString *)jk_sha256String:(NSString *)str
{
    const char *string = str.UTF8String;
    int length = (int)strlen(string);
    unsigned char bytes[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(string, length, bytes);
    return [WHRequestTools jk_stringFromBytes:bytes length:CC_SHA256_DIGEST_LENGTH];
}

+(NSString *)jk_stringFromBytes:(unsigned char *)bytes length:(int)length
{
    NSMutableString *mutableString = @"".mutableCopy;
    for (int i = 0; i < length; i++)
        [mutableString appendFormat:@"%02x", bytes[i]];
    return [NSString stringWithString:mutableString];
}


#pragma mark - 图片压缩
+(NSData*)compressImageToData:(UIImage*)img{
    CGFloat perTemp = 0.9;
    CGFloat per = 1.0;
    int maxSize = 1024;//限制 1M
    
    CGSize imgSize = img.size;
    UIImage *imgTemp = img;
//    NSData *imgData = UIImagePNGRepresentation(imgTemp);
    NSData *imgData = UIImageJPEGRepresentation(imgTemp,1);
    per = perTemp;
    NSInteger lengthg = [imgData length]/1024;
    NSLog(@"img大小 （前） %ld",(long)lengthg);
    if (lengthg > maxSize) {
        CGFloat compressPer = maxSize*0.01/lengthg*0.01;
        
        if (imgSize.width > 4000){
//            imgTemp = [[UIImage alloc]initWithData:imgData];
            imgTemp = [self compressImageToTargetWidth:3000 Image:imgTemp];
            imgData = UIImageJPEGRepresentation(imgTemp, compressPer);
        }else{
            imgData = UIImageJPEGRepresentation(imgTemp, compressPer);
        }
        
//        while (1) {
//            imgTemp = [self compressImageToTargetWidth:imgSize.width*per Image:imgTemp];
//            imgData = UIImageJPEGRepresentation(imgTemp,1);
//            lengthg = [imgData length]/1024;
//            if (lengthg < maxSize) {
//                NSLog(@"img大小 %ld",(long)lengthg);
//                break;
//            }
//            per *= perTemp;
//        }
    }
    return imgData;
}



+(UIImage *)compressImageToTargetWidth:(CGFloat)targetWidth Image:(UIImage*)img{
    
    CGSize imageSize = img.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetHeight = (targetWidth / width) * height;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    
    [img drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

@end
